<template>
  <main class="login">
    <a-form
      class="login-form shadow"
      layout="vertical"
      :model="formRecord"
      @submit="sumbitHandler"
    >
      <a-form-item v-bind="validateInfos.username">
        <a-input v-model:value="formRecord.username" placeholder="Username">
          <template #prefix><UserOutlined /></template>
        </a-input>
      </a-form-item>
      <a-form-item v-bind="validateInfos.password">
        <a-input
          v-model:value="formRecord.password"
          type="password"
          placeholder="Password"
        >
          <template #prefix><LockOutlined /></template>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" block html-type="submit" :disabled="disabled">
          Log in
        </a-button>
      </a-form-item>
    </a-form>
  </main>
</template>
<script>
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import { computed, reactive } from "vue";
import http from "@u/http";
import { useErrorNotice, useSuccessNotice } from "@u/notice";
import { useRoutePathToPage } from "@u/router";
import { useLocalStorage } from "@u/local-storage";
import { Form } from "ant-design-vue";
const useForm = Form.useForm;
export default {
  components: {
    UserOutlined,
    LockOutlined,
  },
  setup() {
    const formRecord = reactive({
      username: "",
      password: "",
    });

    const rules = reactive({
      username: [
        {
          required: true,
          message: "username为必填",
        },
      ],
      password: [
        {
          required: true,
          pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/,
          message: "password必填且含大小写字母与数字8到16位",
        },
      ],
    });

    const { validateInfos } = useForm(formRecord, rules);

    const disabled = computed(() => {
      const status = [
        validateInfos.username.validateStatus,
        validateInfos.password.validateStatus,
      ].every((status) => status === "success");
      return !status;
    });

    const [token] = useLocalStorage("token");
    const toArticlePage = useRoutePathToPage("/manage/articles/1");
    const sumbitHandler = async () => {
      try {
        const res = await http.post("/users/login", formRecord);
        token.value = res.data.token;
        useSuccessNotice({
          message: "登录成功",
          duration: 0.5,
        });
        setTimeout(toArticlePage, 1000);
      } catch (error) {
        useErrorNotice({
          message: "登录失败",
          description: error.reason || "未知错误",
          duration: 2,
        });
      }
    };

    return {
      formRecord,
      disabled,
      sumbitHandler,
      validateInfos,
    };
  },
};
</script>

<style scoped>
.login {
  padding: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form {
  width: 330px;
  padding: 20px;
  background-color: white;
  border: 1px solid #cfd8dc;
  border-radius: 8px;
}
</style>